import json

from celery_tasks.celery import app
from hippo_api.utils.handle_key import AppSetting
from host.models import Host

# 创建任务函数
@app.task
def my_task1(a, b, c):
    print("任务1函数正在执行....")
    return a + b + c

@app.task
def my_task2():
    print("任务2函数正在执行....")

@app.task(name='schedule_task')
def schedule_task(cmd, hosts_ids):
    # 执行传来的指令
    hosts_objs = Host.objects.filter(id__in=hosts_ids)
    result_data = []  # 执行结果
    pkey = AppSetting.get('private_key')

    # 后期可以优化多线程
    for host_obj in hosts_objs:
        cli = host_obj.get_ssh(pkey)
        status, result = cli.exec_command(cmd)
        result_data.append({
            'host_id':host_obj.id,
            'host':host_obj.ip_addr,
            'status':status,
            'result':result
        })
        print('>>>>',status, result)
    return json.dumps(result_data)
